package com.dieusoft.box.trade.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dieusoft.box.info.entity.JzxDefaultCostDetails;
import com.dieusoft.box.info.entity.JzxInfo;
import com.dieusoft.box.info.service.IJzxDefaultCostDetailsService;
import com.dieusoft.box.info.service.IJzxInfoService;
import com.dieusoft.box.info.vo.JzxInfoPage;
import com.dieusoft.box.trade.entity.CostInfo;
import com.dieusoft.box.trade.entity.JzxTrade;
import com.dieusoft.box.trade.service.ICostInfoService;
import com.dieusoft.box.trade.service.IJzxTradeService;
import com.dieusoft.box.trade.vo.JzxTradePage;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 集装箱贸易表
 * @Author: dongw
 * @Date: 2020-10-22
 * @Version: V1.0
 */
@Api(tags = "集装箱贸易表")
@RestController
@RequestMapping("/box.trade/jzxTrade")
@Slf4j
public class JzxTradeController extends JeecgController<JzxTrade, IJzxTradeService> {
    @Autowired
    private IJzxTradeService jzxTradeService;
    @Autowired
    private IJzxDefaultCostDetailsService jzxDefaultCostDetailsService;
    @Autowired
    private ICostInfoService costInfoService;

    @Autowired
    private IJzxInfoService jzxInfoService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页列表查询
     *
     * @param jzxTrade
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */

    @PermissionData(pageComponent = "jzxtrade/JzxTradeList")
    @AutoLog(value = "集装箱贸易表-分页列表查询")
    @ApiOperation(value = "集装箱贸易表-分页列表查询", notes = "集装箱贸易表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(JzxTrade jzxTrade,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<JzxTrade> queryWrapper = QueryGenerator.initQueryWrapper(jzxTrade, req.getParameterMap());
        /**
         * 计算分币种利润额
         * 计算每个箱子的数量和总数
         */
        StringBuffer reMsg = new StringBuffer();
        JSONObject profitDataResJson = new JSONObject();
        JSONObject containerTypeDataResJson = new JSONObject();
        List<JzxTrade> list = jzxTradeService.list(queryWrapper);
        reMsg.append("箱子总数：").append(list.size()).append("台，");
        for (JzxTrade jzxTradeQuery : list) {
            Integer containerTypeCount = containerTypeDataResJson.getInteger(StringUtils.isNotBlank(jzxTradeQuery.getContainerType()) ? jzxTradeQuery.getContainerType() : "其他");
            //统计箱型数量
            if (null == containerTypeCount) {
                containerTypeDataResJson.put(StringUtils.isNotBlank(jzxTradeQuery.getContainerType()) ? jzxTradeQuery.getContainerType() : "其他", 1);
            } else {
                containerTypeDataResJson.put(StringUtils.isNotBlank(jzxTradeQuery.getContainerType()) ? jzxTradeQuery.getContainerType() : "其他", containerTypeCount + 1);
            }
        }
        List<JzxTrade> collect = list.stream().filter(item -> (null != item.getProfit() && null != item.getProfitCurrency()) || (null != item.getProfitDesc() && null != item.getProfitDescCurrency())
        ).collect(Collectors.toList());

        for (JzxTrade jzxTradeFilter : collect) {
            String currentCurrency = null;
            BigDecimal currentPrice = BigDecimal.ZERO;
            //获取这条数据统计的币种和费用
            if (StringUtils.isBlank(jzxTradeFilter.getProfitDescCurrency())) {
                currentCurrency = jzxTradeFilter.getProfitCurrency();
                currentPrice = jzxTradeFilter.getProfit();
            } else {
                currentCurrency = jzxTradeFilter.getProfitDescCurrency();
                currentPrice = new BigDecimal(jzxTradeFilter.getProfitDesc());
            }
            //币种对应的费用
            BigDecimal currencyPrice = profitDataResJson.getBigDecimal(currentCurrency);
            if (null == currencyPrice) {
                profitDataResJson.put(currentCurrency, currentPrice);
            } else {
                profitDataResJson.put(currentCurrency, currencyPrice.add(currentPrice));
            }
        }
        for (Map.Entry<String, Object> entry : containerTypeDataResJson.entrySet()) {
            reMsg.append(entry.getKey() + "：" + entry.getValue() + "台，");
        }
        reMsg.append("总利润额: ");
        for (Map.Entry<String, Object> entry : profitDataResJson.entrySet()) {
            reMsg.append(entry.getValue() + entry.getKey() + "，");
        }
        Page<JzxTrade> page = new Page<JzxTrade>(pageNo, pageSize);
        IPage<JzxTrade> pageList = jzxTradeService.page(page, queryWrapper);
        return Result.OK(pageList).success(reMsg.toString());
    }

    /**
     * 当还箱日期没填根据提货时间来计算出提醒时间
     *
     * @param id
     * @param deliveryTime 提货时间
     * @return
     */
    @GetMapping(value = "/gettipsday")
    public Result getTipsDay(@RequestParam(name = "id") String id, @RequestParam(name = "deliveryTime") String deliveryTime) {
        String keyTipsDay = "tipsDay:" + id;
        boolean boolTipsDay = redisUtil.hasKey(keyTipsDay);
        if (!boolTipsDay) {
            redisUtil.set(keyTipsDay, deliveryTime);
            return Result.OK();
        }
        return Result.OK();
    }

    /**
     * 开始操作
     *
     * @return
     */
    @AutoLog(value = "集装箱贸易表-开始操作订单")
    @ApiOperation(value = "集装箱贸易表-开始操作订单", notes = "集装箱贸易表-开始操作订单")
    @PostMapping(value = "/begin")
    @Deprecated
    public Result beginTrade(@RequestParam("id") String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        JzxTrade jzxTrade = jzxTradeService.getById(id);
//        jzxTrade.setUpdateTime(date);
        jzxTrade.setUpdateBy(sysUser.getUsername());
        jzxTrade.setStatus(2);
        jzxTrade.setOrderStartTime(new Date());
        jzxTradeService.updateById(jzxTrade);
        return Result.OK("订单已开始", null);
    }

    /**
     * 添加
     *
     * @param jzxTradePage
     * @return
     */
    @AutoLog(value = "集装箱贸易表-添加")
    @ApiOperation(value = "集装箱贸易表-添加", notes = "集装箱贸易表-添加")
    @PostMapping(value = "/add")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> add(@RequestBody JzxTradePage jzxTradePage) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        Optional<JzxInfo> jzxInfoOptional = Optional.ofNullable(jzxInfoService.getById(jzxTradePage.getBoxId()));
//        if (!jzxInfoOptional.isPresent()) {
//            return Result.error("集装箱信息不存在");
//        }
        JzxTrade jzxTrade = new JzxTrade();
        BeanUtils.copyProperties(jzxTradePage, jzxTrade);
//        jzxTrade.setBuyBoxCost(null != jzxTradePage.getBuyBoxCost() ? new BigDecimal(jzxTradePage.getBuyBoxCost()) : BigDecimal.ZERO);
//        jzxTrade.setSaleBoxCost(null != jzxTradePage.getSaleBoxCost() ? new BigDecimal(jzxTradePage.getSaleBoxCost()) : BigDecimal.ZERO);
//        jzxTrade.setUseBoxCost(null != jzxTradePage.getUseBoxCost() ? new BigDecimal(jzxTradePage.getUseBoxCost()) : BigDecimal.ZERO);
//        jzxTrade.setIntentionToSellBoxFeel(null != jzxTradePage.getIntentionToSellBoxFeel() ? new BigDecimal(jzxTradePage.getIntentionToSellBoxFeel()) : BigDecimal.ZERO);

        Date date = new Date();

        try {
            jzxTradeService.save(jzxTrade);
        } catch (DuplicateKeyException e) {
            return Result.error(jzxTrade.getContainerNumber() + "的箱号已存在，不能重复新增。");
        }
        if ("2".equals(jzxTrade.getType())) {
//            jzxTrade.setStatus(2);
            //买箱费不为空
            if (null != jzxTrade.getBuyBoxCost()) {
//                List<CostInfo> costInfoListYf = jzxTradePage.getCostInfoListYf();
//                if (null == costInfoListYf) {
//                    costInfoListYf = new ArrayList<>();
//                }
                CostInfo costInfo = new CostInfo();
                costInfo.setCreateBy(sysUser.getUsername());
                costInfo.setCreateTime(date);
                costInfo.setCostName("买箱费");
                costInfo.setCurrency("CNY");
                costInfo.setSettlementCompany(jzxTrade.getCompanyName());
                costInfo.setNum(1);
                costInfo.setStatus("账单未建立");
                costInfo.setPrice(jzxTrade.getBuyBoxCost());
                costInfo.setTotalPrice(jzxTrade.getBuyBoxCost());
                costInfo.setCnyAmount(jzxTrade.getBuyBoxCost());
                costInfo.setRate("1");
                costInfo.setType("yf");
                costInfo.setStatus("录入状态");
                costInfo.setBuisId(jzxTrade.getId());
                costInfo.setBillType("应付");
                costInfo.setChargingUnit("bill");
                costInfo.setBuisId(jzxTrade.getId());
//                costInfoListYf.add(costInfo);
//                jzxTradePage.setCostInfoListYf(costInfoListYf);
                costInfoService.save(costInfo);
            }
            if (null != jzxTrade.getSaleBoxCost()) {
//                List<CostInfo> costInfoListYs = jzxTradePage.getCostInfoListYs();
//                if (null == costInfoListYs) {
//                    costInfoListYs = new ArrayList<>();
//                }
                CostInfo costInfo = new CostInfo();
                costInfo.setCreateBy(sysUser.getUsername());
                costInfo.setCreateTime(date);
                costInfo.setCostName("卖箱费");
                costInfo.setCurrency("CNY");
                costInfo.setSettlementCompany(jzxTrade.getCompanyName());
                costInfo.setNum(1);
                costInfo.setCnyAmount(jzxTrade.getBuyBoxCost());
                costInfo.setStatus("账单未建立");
                costInfo.setPrice(jzxTrade.getBuyBoxCost());
                costInfo.setTotalPrice(jzxTrade.getBuyBoxCost());
                costInfo.setRate("1");
                costInfo.setType("ys");
                costInfo.setStatus("录入状态");
                costInfo.setBuisId(jzxTrade.getId());
                costInfo.setBillType("应收");
                costInfo.setChargingUnit("bill");
                costInfo.setBuisId(jzxTrade.getId());
                costInfoService.save(costInfo);
//                costInfoListYs.add(costInfo);
//                jzxTradePage.setCostInfoListYs(costInfoListYs);
            }
        }
//        jzxTradeService.saveMain(jzxTrade, jzxTradePage.getJzxDefaultCostDetailsList(), jzxTradePage.getCostInfoListYs(), jzxTradePage.getCostInfoListYf());
        //TODO 箱子的状态不随箱贸的业务变化而变化
//        if (StringUtils.isNotBlank(jzxTrade.getContainerNumber())) {
//            QueryWrapper<JzxInfo> jzxInfoQueryWrapper = new QueryWrapper<>();
//            jzxInfoQueryWrapper.eq("container_number", jzxTrade.getContainerNumber());
//            JzxInfo jzxInfo = jzxInfoService.getOne(jzxInfoQueryWrapper);
//            if (null != jzxInfo) {
//                jzxInfo.setUpdateBy(sysUser.getUsername());
//                jzxInfo.setUpdateTime(date);
//                jzxInfo.setStatus(0);//修改集装箱状态为"使用中"
//                jzxInfoService.updateById(jzxInfo);
//            }
//
//        }

        return Result.OK(jzxTrade.getId()).success("添加成功");
    }

    /**
     * 还箱
     *
     * @param jzxTradePage
     * @return
     */
    @AutoLog(value = "集装箱贸易表-还箱")
    @ApiOperation(value = "集装箱贸易表-还箱", notes = "集装箱贸易表-还箱")
    @PostMapping(value = "/returnbox")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> returnBox(@RequestBody JzxTradePage jzxTradePage) {
        Optional<JzxTrade> jzxTradeOptional = Optional.ofNullable(jzxTradeService.getById(jzxTradePage.getId()));
        if (jzxTradeOptional.isPresent()) {
            //TODO 箱贸业务不涉及修改集装箱的状态
//            Optional<JzxInfo> jzxInfoOptional = Optional.ofNullable(jzxInfoService.getById(jzxTradeOptional.get().getBoxId()));
//            if (!jzxInfoOptional.isPresent()) {
//                return Result.error("集装箱信息不存在");
//            }
            JzxTrade jzxTrade = new JzxTrade();
            BeanUtils.copyProperties(jzxTradePage, jzxTrade);
            //更新集装箱信息
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//            JzxInfo jzxInfo = jzxInfoOptional.get();
//            jzxInfo.setStatus(1);
//            jzxInfo.setUpdateBy(sysUser.getUsername());
////            jzxInfo.setUpdateTime(new Date());
//
//            jzxInfo.setPod(jzxTrade.getPod());
//            jzxInfo.setContainerPlace(jzxTrade.getPodYardInfo());
//            jzxInfo.setInTime(jzxTrade.getPodReturnboxTime());
//
//            jzxInfoService.updateById(jzxInfo);
            //更新箱贸信息
//            jzxTrade.setUpdateTime(new Date());
            jzxTrade.setUpdateBy(sysUser.getUsername());
            jzxTrade.setStatus(3);
            jzxTradeService.updateById(jzxTrade);
            return Result.OK("还箱成功！");
        }
        return Result.error("订单不存在");

    }

    @AutoLog(value = "集装箱贸易表-复制")
    @ApiOperation(value = "集装箱贸易表-复制", notes = "集装箱贸易表-复制")
    @PostMapping(value = "/copy")
    @Transactional(rollbackOn = Exception.class)
    @Deprecated
    public Result copy(String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        JzxTrade jzxTrade = jzxTradeService.getById(id);
        JzxTrade newData = new JzxTrade();
        BeanUtils.copyProperties(jzxTrade, newData);
        newData.setId(null);
        newData.setCreateTime(new Date());
        newData.setCreateBy(sysUser.getRealname());
        jzxTradeService.save(newData);
        return Result.OK();
    }


    private void updateJzxInfo(String boxId, Integer status) {
        Optional<JzxInfo> jzxInfoOptional = Optional.ofNullable(jzxInfoService.getById(boxId));
        if (jzxInfoOptional.isPresent()) {
            JzxInfo jzxInfo = jzxInfoOptional.get();
            jzxInfo.setStatus(status);
            jzxInfoService.updateById(jzxInfo);
        }
    }

    /**
     * 编辑
     *
     * @param jzxTradePage
     * @return
     */
    @AutoLog(value = "集装箱贸易表-编辑")
    @ApiOperation(value = "集装箱贸易表-编辑", notes = "集装箱贸易表-编辑")
    @PutMapping(value = "/edit")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> edit(@RequestBody JzxTradePage jzxTradePage) {
        JzxTrade jzxTrade = new JzxTrade();
        BeanUtils.copyProperties(jzxTradePage, jzxTrade);
//        jzxTrade.setBuyBoxCost(null != jzxTradePage.getBuyBoxCost() ? new BigDecimal(jzxTradePage.getBuyBoxCost()) : BigDecimal.ZERO);
//        jzxTrade.setSaleBoxCost(null != jzxTradePage.getSaleBoxCost() ? new BigDecimal(jzxTradePage.getSaleBoxCost()) : BigDecimal.ZERO);
//        jzxTrade.setUseBoxCost(null != jzxTradePage.getUseBoxCost() ? new BigDecimal(jzxTradePage.getUseBoxCost()) : BigDecimal.ZERO);
//        jzxTrade.setIntentionToSellBoxFeel(null != jzxTradePage.getIntentionToSellBoxFeel() ? new BigDecimal(jzxTradePage.getIntentionToSellBoxFeel()) : BigDecimal.ZERO);


        JzxTrade jzxTradeEntity = jzxTradeService.getById(jzxTrade.getId());
        if (jzxTradeEntity == null) {
            return Result.error("未找到对应数据");
        }
        //根据提货时间来判断是否要修改提醒周期
        if (null != jzxTrade.getPodDeliveryTime()) {
            String strDeliveryTime = DateUtils.formatDate(jzxTrade.getPodDeliveryTime());
            boolean hasKey = redisUtil.hasKey("tipsDay:" + jzxTrade.getId());
            if (hasKey) {
                Object o = redisUtil.get("tipsDay:" + jzxTrade.getId());
                //如果该条数据提货时间出现过小红点且本次修改的提货时间与上次提醒的提货时间不一致则修改提醒周期为3填
                if (!strDeliveryTime.equals(o.toString())) {
                    jzxTrade.setTipsDay(3);
                }
            }
        }
        //如果编辑时候修改了集装箱信息，要对原来的集装箱进行释放
        //TODO 箱贸业务不涉及修改集装箱的状态
//        String OldBoxId = jzxTradeEntity.getBoxId();
//        String boxId = jzxTrade.getBoxId();
//        if (!OldBoxId.equals(boxId)) {
//            updateJzxInfo(OldBoxId, 1);
//            updateJzxInfo(boxId, 0);
//        }
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        if ("2".equals(jzxTrade.getType())) {
//            Date date = new Date();
//            //买箱费不为空
//            if (null != jzxTrade.getBuyBoxCost().toString()) {
//                List<CostInfo> costInfoListYf = jzxTradePage.getCostInfoListYf();
//                if (null != costInfoListYf) {
//                    costInfoListYf = new ArrayList<>();
//                    CostInfo costInfo = new CostInfo();
//                    costInfo.setCreateBy(sysUser.getUsername());
//                    costInfo.setCreateTime(date);
//                    costInfo.setCostName("BUYBOXCOST");
//                    costInfo.setCurrency("CNY");
//                    costInfo.setSettlementCompany(jzxTrade.getCompanyName());
//                    costInfo.setNum(1);
//                    costInfo.setStatus("账单未建立");
//                    costInfo.setPrice(jzxTrade.getBuyBoxCost());
//                    costInfo.setTotalPrice(jzxTrade.getBuyBoxCost());
//                    costInfo.setRate("1");
//                    costInfo.setType("yf");
//                    costInfo.setBuisId(jzxTrade.getId());
//                    costInfo.setBillType("应付");
//                    costInfo.setChargingUnit("bill");
//                    costInfoListYf.add(costInfo);
//                    jzxTradePage.setCostInfoListYf(costInfoListYf);
//                } else {
//                    List<CostInfo> saleBoxCostList = costInfoListYf.stream().filter(item ->
//                            item.getCostName().equals("SALEBOXCOST")
//                    ).collect(Collectors.toList());
//                    if (saleBoxCostList.size() == 0) {
//                        costInfoListYf = new ArrayList<>();
//                        CostInfo costInfo = new CostInfo();
//                        costInfo.setCreateBy(sysUser.getUsername());
//                        costInfo.setCreateTime(date);
//                        costInfo.setCostName("BUYBOXCOST");
//                        costInfo.setCurrency("CNY");
//                        costInfo.setSettlementCompany(jzxTrade.getCompanyName());
//                        costInfo.setNum(1);
//                        costInfo.setStatus("账单未建立");
//                        costInfo.setPrice(jzxTrade.getBuyBoxCost());
//                        costInfo.setTotalPrice(jzxTrade.getBuyBoxCost());
//                        costInfo.setRate("1");
//                        costInfo.setType("yf");
//                        costInfo.setBuisId(jzxTrade.getId());
//                        costInfo.setBillType("应付");
//                        costInfo.setChargingUnit("bill");
//                        costInfoListYf.add(costInfo);
//                        jzxTradePage.setCostInfoListYf(costInfoListYf);
//                    }
//                }
//
//            }
//            if (null != jzxTrade.getSaleBoxCost().toString()) {
//                List<CostInfo> costInfoListYs = jzxTradePage.getCostInfoListYs();
//                if (null != costInfoListYs) {
//                    costInfoListYs = new ArrayList<>();
//                    CostInfo costInfo = new CostInfo();
//                    costInfo.setCreateBy(sysUser.getUsername());
//                    costInfo.setCreateTime(date);
//                    costInfo.setCostName("SALEBOXCOST");
//                    costInfo.setCurrency("CNY");
//                    costInfo.setSettlementCompany(jzxTrade.getCompanyName());
//                    costInfo.setNum(1);
//                    costInfo.setStatus("账单未建立");
//                    costInfo.setPrice(jzxTrade.getBuyBoxCost());
//                    costInfo.setTotalPrice(jzxTrade.getBuyBoxCost());
//                    costInfo.setRate("1");
//                    costInfo.setType("ys");
//                    costInfo.setBuisId(jzxTrade.getId());
//                    costInfo.setBillType("应收");
//                    costInfo.setChargingUnit("bill");
//                    costInfoListYs.add(costInfo);
//                    jzxTradePage.setCostInfoListYs(costInfoListYs);
//                } else {
//                    List<CostInfo> saleBoxCostList = costInfoListYs.stream().filter(item ->
//                            item.getCostName().equals("SALEBOXCOST")
//                    ).collect(Collectors.toList());
//                    if (saleBoxCostList.size() == 0) {
//                        costInfoListYs = new ArrayList<>();
//                        CostInfo costInfo = new CostInfo();
//                        costInfo.setCreateBy(sysUser.getUsername());
//                        costInfo.setCreateTime(date);
//                        costInfo.setCostName("SALEBOXCOST");
//                        costInfo.setCurrency("CNY");
//                        costInfo.setSettlementCompany(jzxTrade.getCompanyName());
//                        costInfo.setNum(1);
//                        costInfo.setStatus("账单未建立");
//                        costInfo.setPrice(jzxTrade.getBuyBoxCost());
//                        costInfo.setTotalPrice(jzxTrade.getBuyBoxCost());
//                        costInfo.setRate("1");
//                        costInfo.setType("ys");
//                        costInfo.setBuisId(jzxTrade.getId());
//                        costInfo.setBillType("应收");
//                        costInfo.setChargingUnit("bill");
//                        costInfoListYs.add(costInfo);
//                        jzxTradePage.setCostInfoListYs(costInfoListYs);
//                    }
//                }
//            }
//        }
        try {
            jzxTradeService.updateById(jzxTrade);
        } catch (DuplicateKeyException e) {
            return Result.error(jzxTrade.getContainerNumber() + "的箱号已存在，不能重复新增。");
        }

//        jzxTradeService.updateMain(jzxTrade, jzxTradePage.getJzxDefaultCostDetailsList(), jzxTradePage.getCostInfoListYs(), jzxTradePage.getCostInfoListYf());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "集装箱贸易表-通过id删除")
    @ApiOperation(value = "集装箱贸易表-通过id删除", notes = "集装箱贸易表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        Optional<JzxTrade> jzxTradeOptional = Optional.ofNullable(jzxTradeService.getById(id));
        if (jzxTradeOptional.isPresent()) {
            JzxTrade jzxTrade = jzxTradeOptional.get();
            String boxId = jzxTrade.getBoxId();
            updateJzxInfo(boxId, 1);
            jzxTradeService.delMain(id);
            return Result.OK("删除成功!");
        }
        return Result.error("订单不存在");
    }

    /**
     * 国内贸易还箱
     *
     * @param id
     * @return
     */
    @AutoLog(value = "集装箱贸易表-国内贸易还箱")
    @ApiOperation(value = "集装箱贸易表-国内贸易还箱", notes = "集装箱贸易表-国内贸易还箱")
    @PostMapping(value = "/complete")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> complete(@RequestParam(name = "id", required = true) String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Optional<JzxTrade> jzxTradeOptional = Optional.ofNullable(jzxTradeService.getById(id));
        if (jzxTradeOptional.isPresent()) {
            JzxTrade jzxTrade = jzxTradeOptional.get();
            //TODO 箱贸业务不涉及修改集装箱的状态
//            updateJzxInfo(jzxTrade.getBoxId(), 1);
            jzxTrade.setUpdateBy(sysUser.getUsername());
//            jzxTrade.setUpdateTime(new Date());
            jzxTrade.setStatus(3);
            jzxTradeService.updateById(jzxTrade);
            return Result.OK("还箱成功", "");
        }
        return Result.error("订单信息不存在");
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "集装箱贸易表-批量删除")
    @ApiOperation(value = "集装箱贸易表-批量删除", notes = "集装箱贸易表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.jzxTradeService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "集装箱贸易表-通过id查询")
    @ApiOperation(value = "集装箱贸易表-通过id查询", notes = "集装箱贸易表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        JzxTrade jzxTrade = jzxTradeService.getById(id);
        if (jzxTrade == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(jzxTrade);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "目的港堆场收费费率通过主表ID查询")
    @ApiOperation(value = "目的港堆场收费费率主表ID查询", notes = "目的港堆场收费费率-通主表ID查询")
    @GetMapping(value = "/queryJzxDefaultCostDetailsByMainId")
    public Result<?> queryJzxDefaultCostDetailsListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<JzxDefaultCostDetails> jzxDefaultCostDetailsList = jzxDefaultCostDetailsService.selectByMainId(id);
        return Result.OK(jzxDefaultCostDetailsList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "费用信息")
    @ApiOperation(value = "费用信息", notes = "费用信息-通主表ID查询")
    @GetMapping(value = "/queryCostInfoByMainId")
    public Result<?> queryCostInfoListByMainId(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "type", required = true) String type) {
        List<CostInfo> costInfoList = costInfoService.selectByMainId(id, type);
        return Result.OK(costInfoList);
    }

    /**
     * 通过账单号查询费用信息
     *
     * @param billNumber
     * @return
     */
    @AutoLog(value = "通过账单号查询费用信息")
    @ApiOperation(value = "通过账单号查询费用信息", notes = "费用信息-通过账单号查询费用信息")
    @GetMapping(value = "/queryCostInfoByBillNumber")
    public Result<?> queryCostInfoListByBillNumber(@RequestParam(name = "billNumber", required = true) String billNumber) {
        List<CostInfo> costInfoList = costInfoService.selectByBillNumber(billNumber);
        return Result.OK(costInfoList);
    }


    /**
     * 导出excel
     *
     * @param request
     * @param jzxTrade
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, JzxTrade jzxTrade) {
        // Step.1 组装查询条件查询数据
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<JzxTrade> queryWrapper = QueryGenerator.initQueryWrapper(jzxTrade, request.getParameterMap());
        queryWrapper.eq("sys_org_code", sysUser.getOrgCode());
        //Step.2 获取导出数据
        List<JzxTrade> queryList = jzxTradeService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<JzxTrade> jzxTradeList = new ArrayList<JzxTrade>();
        if (oConvertUtils.isEmpty(selections)) {
            jzxTradeList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            jzxTradeList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<JzxTradePage> pageList = new ArrayList<JzxTradePage>();
        for (JzxTrade main : jzxTradeList) {
            JzxTradePage vo = new JzxTradePage();
            BeanUtils.copyProperties(main, vo);
            if (null == vo.getPolDesc()) {
                vo.setPolDesc(vo.getPol());
            }
            if (null == vo.getPodDesc()) {
                vo.setPodDesc(vo.getPod());
            }
            if ("1".equals(vo.getType())) {
                vo.setType("国际箱贸业务");
            } else if ("2".equals(vo.getType())) {
                vo.setType("国内箱贸业务");
            } else if ("3".equals(vo.getType())) {
                vo.setType("租箱业务");
            }
//            vo.setBuyBoxCost((null == vo.getBuyBoxCostCurrency() ? "" : vo.getBuyBoxCostCurrency()) + (null == vo.getBuyBoxCost() ? "0.00" : vo.getBuyBoxCost()));
//            vo.setSaleBoxCost((null == vo.getSaleBoxCostCurrency() ? "" : vo.getSaleBoxCostCurrency()) + (null == vo.getSaleBoxCost() ? "0.00" : vo.getSaleBoxCost()));
//            vo.setIntentionToSellBoxFeel((null == vo.getIntentionToSellBoxFeelCurrency() ? "" : vo.getIntentionToSellBoxFeelCurrency()) + (null == vo.getIntentionToSellBoxFeel() ? "0.00" : vo.getIntentionToSellBoxFeel()));
//            vo.setUseBoxCost((null == vo.getUseBoxCostCurrency() ? "" : vo.getUseBoxCostCurrency()) + (null == vo.getUseBoxCost() ? "0.00" : vo.getUseBoxCost()));
//            if (null == vo.getProfitDesc()) {
//                vo.setProfitDesc(null == vo.getProfitCurrency() ? "" : vo.getProfitCurrency() + (null == vo.getProfit() ? "" : vo.getProfit().toString()));
//            } else {
//                vo.setProfitDesc((null == vo.getProfitDescCurrency() ? "" : vo.getProfitDescCurrency()) + vo.getProfitDesc());
//            }

            if (StringUtils.isBlank(vo.getPodYardTotalCostDesc())) {
                vo.setPodYardTotalCostDesc(null == vo.getPodYardTotalCost() ? "0.00" : vo.getPodYardTotalCost().toString());
            }

            pageList.add(vo);
        }
        String[] cols = request.getParameter("field").split(",");
        List filterCols = new ArrayList();
        for (String str : cols) {
            if (StringUtils.isNoneBlank(str) && !"action".equals(str) && !"id".equals(str) && !"status".equals(str)) {
                filterCols.add(str.replaceAll("_dictText", ""));
            }
        }

        String exportFields = Joiner.on(",").join(filterCols);
        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "集装箱贸易表");
        mv.addObject(NormalExcelConstants.CLASS, JzxTradePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("集装箱贸易表", "导出人:" + sysUser.getRealname(), "集装箱贸易表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        mv.addObject(NormalExcelConstants.EXPORT_FIELDS, exportFields);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @Transactional(rollbackOn = Exception.class)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<JzxTradePage> list = ExcelImportUtil.importExcel(file.getInputStream(), JzxTradePage.class, params);
                boolean isGo = false;
                boolean isGo1 = false;
                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                List<String> repeatData = new LinkedList<>();
                for (JzxTradePage page : list) {
                    JzxTradePage po = new JzxTradePage();
                    BeanUtils.copyProperties(page, po);
//                    jzxInfoService.saveMain(po, page.getJzxDefaultCostDetailsList());
                    //判断非空字段是否有值
                    if (null == po.getContainerNumber() || null == po.getContainerType() || null == po.getType()) {
                        isGo = true;
                        break;
                    }
                    if (!"国际箱贸业务".equals(po.getType().trim()) && !"国内箱贸业务".equals(po.getType().trim()) && !"租箱业务".equals(po.getType().trim())) {
                        isGo1 = true;
                        break;
                    }

                    //查询是否存在相同的箱号
                    QueryWrapper<JzxTrade> jzxTradeQueryWrapper = new QueryWrapper<>();
                    jzxTradeQueryWrapper.eq("container_number", po.getContainerNumber());
                    jzxTradeQueryWrapper.eq("sys_org_code", sysUser.getOrgCode());
                    JzxTrade ji = jzxTradeService.getOne(jzxTradeQueryWrapper);
                    if (null != ji) {
                        repeatData.add(po.getContainerNumber());
                    }
                }

                if (isGo) {
                    return Result.error("表格中存在箱型、箱号或业务类型为空的数据");
                }
                if (isGo1) {
                    return Result.error("业务类型必须为：国际箱贸业务、国内箱贸业务或租箱业务");
                }
                if (repeatData.size() > 0) {
                    return Result.error("下面箱号已存在不能重复添加。" + Joiner.on(",").join(repeatData));
                }
                for (JzxTradePage page : list) {
                    JzxTrade po = new JzxTrade();
                    BeanUtils.copyProperties(page, po);
                    if (page.getType().equals("国际箱贸业务")) {
                        po.setType("1");
                    } else if (page.getType().equals("国内箱贸业务")) {
                        po.setType("2");
                    } else if (page.getType().equals("租箱业务")) {
                        po.setType("3");
                    }

//                    if (page.getConditionType().equals("新箱")) {
//                        po.setConditionType("1");
//                    } else if (page.getConditionType().equals("旧箱")) {
//                        po.setConditionType("2");
//                    } else {
//                        po.setConditionType("");
//                    }

                    try {
                        jzxTradeService.save(po);
                    } catch (DuplicateKeyException e) {
                        return Result.error(po.getContainerNumber() + "的箱号已存在，不能重复新增。");
                    }
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }
}
